import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  getRefToken,
  removeToken
} from '@/utils/auth'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL:'http://localhost:5000/v1/',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 0 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation

      if (config.url.indexOf("refresh") > -1) {
        config.headers['Authorization'] = getRefToken()
      } else {
        config.headers['Authorization'] = getToken()
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code > 300) {
      Message({
        message: res.msg || 'Error',
        type222: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    const response = error.response;
    console.log(response)

    if (response.status == 401 && response.data.msg == 'token 无效') {

      if (response.data.request.indexOf('pic_history') !== -1) {
        Message({
          message: '未登录，不支持查看历史图片',
          type222: 'info',
          duration: 1 * 1000
        })
      } else if (response.data.request.indexOf('refresh') !== -1) {
        router.push({
          path: '/login'
        })
      } else {
        MessageBox.confirm('登录过期，您可以选择重新登录留着该页面', '确认登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type222: 'warning'
        }).then(() => {
          store.dispatch('user/tokenRefresh').then(() => {
            location.reload()
          }).catch(() => {
            removeToken()
            router.push({
              path: '/login'
            })
          })
        }).catch(() => {
          removeToken()
          router.push({
            path: '/login'
          })
        })
      }

    } else {


      if (response.data) {
        var msg = response.data.msg
      } else {
        var msg = error.message
      }

      Message({
        message: msg,
        type222: 'error',
        duration: 5 * 1000
      })


      if (response.config.url.indexOf('init_ticket_airline') > -1) {
        return response.data
      }
    }
    return Promise.reject(error)
  }
)

export default service
